package com.cy.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cy.entity.JsonResult;
import com.cy.entity.Manager;
import com.cy.entity.Meetingroom;
import com.cy.service.ManagerService;
import com.cy.service.MeetingroomService;

@RestController
public class ManagerController {
	@Autowired
	private ManagerService service;
	
	@Autowired
	private MeetingroomService meetingroomService;
	
	@RequestMapping("findAllManager")
	public JsonResult findAllManager() {
		List<Manager> list = service.findAllManager();
		return new JsonResult<>(list);
	}
	
	@RequestMapping("findManagerById")
	public JsonResult findManagerById(Integer id) {
		Manager manager = service.findManagerById(id);
		return new JsonResult<>(manager);
	}
	
	
	@RequestMapping("findByManagerTelForFuzzy")
	public JsonResult findByManagerTelForFuzzy(String tel) {
		List<Manager> list = service.findByManagerTelForFuzzy(tel);
		return new JsonResult<>(list);
	}
	@RequestMapping("addManager")
	public JsonResult addManager(String managerName, String managerTel) {
		Manager manager = new Manager(managerTel,managerName);
		if (service.findByManagerTel(manager.getManagertel()).size()>0) {
			return new JsonResult(1,"该手机号用户已经是管理员了");
		}
		service.addManager(manager);
		return new JsonResult<>(0, "添加成功");
	}
	 
	@RequestMapping("updateManager")
	public JsonResult updateManager(Integer managerId,String tel,String name) {
		Manager manager = service.findManagerById(managerId);
		List<Manager> list = service.findByManagerTel(tel);
		if(list.size()>0) {
			System.out.println(list.get(0).getManagerid()+" "+managerId);
			if(!list.get(0).getManagerid().equals(managerId)) {
				return new JsonResult<>(1,"该手机号已经被他人注册！");
			}
		}
		manager.setManagertel(tel);
		manager.setManagername(name);
		service.updateManager(manager);
		return new JsonResult<>(0,"修改成功！");
	}
	
	@RequestMapping("deleteManager")
	public JsonResult deleteManager(Integer managerId) {
		List<Meetingroom> mrs =  meetingroomService.findAllMeetingroom();
		List<Integer> idList = new ArrayList<>();
		for (int i = 0; i < mrs.size(); i++) {
			idList.add(mrs.get(i).getManagerid());
		}
		if (idList.contains(managerId)) {
			return new JsonResult<>(1,"删除失败！无法删除最后一个管理员");
		}
		service.deleteManager(managerId);
		return new JsonResult<>("success");
	}
}
